package tw.asap.plus.presenter;

import android.content.Context;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import tw.asap.plus.entity.CartBean;
import tw.asap.plus.entity.SubCartBean;
import tw.asap.plus.entity.response.GoodsDetailNV;
import tw.asap.plus.ui.adapter.CartListAdapter;
import tw.asap.plus.ui.adapter.PinedSectionAdapter;
import tw.asap.plus.ui.custom.CartView;

/**
 * Created by Yax on 15/11/13.
 */
public class CartPresenterImpl implements CartPresenter {

    private String shopKey;
    private CartView cartView;
    private Context context;
    private ArrayList<PinedSectionAdapter.GoodsItem> goodsItems;
    private ArrayList<PinedSectionAdapter.GoodsItem> categoryList;
    private ArrayList<CartBean> cartList = new ArrayList<>();
    private HashMap<String, PinedSectionAdapter.GoodsItem> selectedGoodsItemHashMap = new HashMap<>();
    int totalCount = 0;
    int summery = 0;
    private Adapter adapter;
    private ListAdapter secAdapter;
    CartListAdapter cartListAdapter;

    public CartPresenterImpl(Context context, String shopKey) {
        this.shopKey = shopKey;
        this.context = context;
    }

    @Override
    public void add(PinedSectionAdapter.GoodsItem goods) {
        add(goods, true);
    }

    //避免所有物品都刷新，可将notifyMainList设为false
    public void add(PinedSectionAdapter.GoodsItem goods, boolean notifyMainList) {
        goodsItems.get(goods.listPosition).count++;
        categoryList.get(goods.sectionPosition).sectionContainCount++;
        totalCount++;
        summery += Integer.parseInt(goods.itemEntity.getPrice());
        double result = Double.parseDouble(String.valueOf(summery));
        cartView.setSummery(String.format("%.2f", result / 100));
        CartBean cartBean = getCartBeanPosition(goods.itemEntity.getId());
        if (cartBean != null) {
            cartBean.item_nums = String.valueOf(Integer.parseInt(cartBean.item_nums) + 1);
        } else {
            cartList.add(new CartBean(goods.itemEntity.getId(), "1", getItemById(goods.itemEntity.getId())));
        }
        if (!selectedGoodsItemHashMap.containsKey(goods.itemEntity.getId())) {
            selectedGoodsItemHashMap.put(goods.itemEntity.getId(), goods);
        }
        cartView.setQuantityText(totalCount);
        cartListAdapter.notifyDataSetChanged();
        if (notifyMainList)
            notifyData();
        observable.notifyObservers(cartBean);
    }

    private CartBean getCartBeanPosition(String goodsId) {
        for (int i = 0; i < cartList.size(); i++) {
            if (cartList.get(i).getItem_id().equals(goodsId)) {
                return cartList.get(i);
            }
        }
        return null;
    }

    private Observable observable = new Observable() {
        @Override
        public void notifyObservers(Object data) {
            setChanged();
            super.notifyObservers(data);
        }
    };

    public void registerObserver(Observer observer) {
        observable.addObserver(observer);
    }

    public void unRegisterObserver(Observer observer) {
        observable.deleteObserver(observer);
    }

    @Override
    public void minus(PinedSectionAdapter.GoodsItem goods) {
        minus(goods, true);
    }

    public void minus(PinedSectionAdapter.GoodsItem goods, boolean notifyMainList) {
        goodsItems.get(goods.listPosition).count--;
        categoryList.get(goods.sectionPosition).sectionContainCount--;
        summery -= Integer.parseInt(goods.itemEntity.getPrice());
        totalCount--;
        double result = Double.parseDouble(String.valueOf(summery));
        cartView.setSummery(String.format("%.2f", result / 100));
        cartView.setQuantityText(totalCount);
        CartBean cartBean = getCartBeanPosition(goods.itemEntity.getId());
        if (cartBean != null) {
            if (cartBean.item_nums.equals("1")) {
                cartList.remove(cartBean);
                cartBean.item_nums = "0";
            } else {
                cartBean.item_nums = String.valueOf(Integer.parseInt(cartBean.item_nums) - 1);
            }
        }
        if (selectedGoodsItemHashMap.containsKey(goods.itemEntity.getId()) && goodsItems.get(goods.listPosition).count == 0) {
            selectedGoodsItemHashMap.remove(goods.itemEntity.getId());
        }
        cartListAdapter.notifyDataSetChanged();
        if (notifyMainList)
            notifyData();
        observable.notifyObservers(cartBean);
    }


    @Override
    public List<CartBean> getCartGoodsList() {
        return cartList;
    }

    private PinedSectionAdapter.GoodsItem getItemById(String key) {
        if (goodsItems != null) {
            for (PinedSectionAdapter.GoodsItem goods : goodsItems) {
                if (goods.type == PinedSectionAdapter.GoodsItem.ITEM && goods.itemEntity.getId().equals(key)) {
                    return goods;
                }
            }
        }
        return null;
    }

    @Override
    public void bindView(CartView cartView, CartCheckoutListener listener) {
        this.cartView = cartView;
        cartView.setQuantityText(totalCount);
        double result = Double.parseDouble(String.valueOf(summery));
        cartView.setSummery(String.format("%.2f", result / 100));
        cartView.setOnCheckListener(listener);
        cartListAdapter = new CartListAdapter(context, cartList, this);
        cartView.setCartAdapter(cartListAdapter);
        cartView.setOnOpenListener(new CartListOpenListener() {
            @Override
            public void onOpen() {
                getCartGoodsList();
            }
        });
        cartListAdapter.notifyDataSetChanged();
    }

    @Override
    public void setOnCheckListener(CartCheckoutListener listener) {
        if (cartView != null) {
            cartView.setOnCheckListener(listener);
        }
    }

    @Override
    public void bindGoodsList(ArrayList list) {
        this.goodsItems = list;
    }

    @Override
    public void notifyData() {
        if (adapter != null) {
            ((BaseAdapter) adapter).notifyDataSetChanged();
        }

        if (secAdapter != null) {
            ((BaseAdapter) secAdapter).notifyDataSetChanged();
        }

    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        this.adapter = adapter;
    }

    @Override
    public void setSecondAdapter(ListAdapter adapter) {
        this.secAdapter = adapter;
    }

    @Override
    public void bindCategoryList(ArrayList<PinedSectionAdapter.GoodsItem> categoryList) {
        this.categoryList = categoryList;
    }

    @Override
    public void clearCart() {
        totalCount = 0;
        summery = 0;
        Iterator iterator = selectedGoodsItemHashMap.entrySet().iterator();
        if (!iterator.hasNext()) {
            return;
        }
        while (iterator.hasNext()) {
            Map.Entry<String, PinedSectionAdapter.GoodsItem> entry = (Map.Entry<String, PinedSectionAdapter.GoodsItem>) iterator.next();
            goodsItems.get(entry.getValue().listPosition).count = 0;
            goodsItems.get(entry.getValue().listPosition).hasSub = false;
            goodsItems.get(entry.getValue().listPosition).subList.clear();
            categoryList.get(entry.getValue().sectionPosition).sectionContainCount = 0;
        }
        cartList.clear();
        cartListAdapter.notifyDataSetChanged();
        notifyData();
        observable.notifyObservers(-1);
        cartView.reset();
    }

    @Override
    public void addSubItem(SubCartBean subCartBean, PinedSectionAdapter.GoodsItem goodsItem) {
        addSubItem(subCartBean, goodsItem, false);
    }

    public void addSubItem(SubCartBean subCartBean, PinedSectionAdapter.GoodsItem goodsItem, boolean isNotifyData) {
        goodsItems.get(goodsItem.listPosition).count += subCartBean.getCount();
        categoryList.get(goodsItem.sectionPosition).sectionContainCount += subCartBean.getCount();
        totalCount += subCartBean.getCount();
        summery += (Integer.parseInt(goodsItem.itemEntity.getPrice()) * subCartBean.getCount());
        double result = Double.parseDouble(String.valueOf(summery));
        cartView.setSummery(String.format("%.2f", result / 100));
        CartBean cartBean = getCartBeanPosition(goodsItem.itemEntity.getId());
        if (cartBean != null) {
            if (cartBean.goodsInfo.hasSub && cartBean.goodsInfo.subList != null && cartBean.goodsInfo.subList.size() > 0) {
                boolean hasCurrentSub = false;
                for (SubCartBean subBean : cartBean.goodsInfo.subList) {
                    for (String key : subBean.getPropertyMap().keySet()) {
                        if (!subCartBean.getPropertyMap().containsKey(key)) {
                            continue;
                        }
                        GoodsDetailNV.PropsEntity.ValuesEntity value = subCartBean.getPropertyMap().get(key);
                        if (value != null && value.equals(subBean.getPropertyMap().get(key))) {
                            subBean.setCount(subBean.getCount() + subCartBean.getCount());
                            hasCurrentSub = true;
                            break;
                        }
                    }
                    if (hasCurrentSub) {
                        break;
                    }
                }
                if (!hasCurrentSub) {
                    cartBean.goodsInfo.subList.add(subCartBean);
                }
            } else {
                cartBean.goodsInfo.subList = new ArrayList<>();
                cartBean.goodsInfo.subList.add(subCartBean);
                cartBean.goodsInfo.hasSub = true;
            }
            cartBean.item_nums = String.valueOf(Integer.parseInt(cartBean.item_nums) + subCartBean.getCount());
        } else {
            CartBean cartBean1 = new CartBean(goodsItem.itemEntity.getId(), String.valueOf(subCartBean.getCount()),
                    getItemById(goodsItem.itemEntity.getId()));
            cartBean1.goodsInfo.hasSub = true;
            cartBean1.goodsInfo.subList = new ArrayList<>();
            cartBean1.goodsInfo.subList.add(subCartBean);
            cartBean1.goodsInfo.count = subCartBean.getCount();
            cartList.add(cartBean1);
        }


        if (!selectedGoodsItemHashMap.containsKey(goodsItem.itemEntity.getId())) {
            selectedGoodsItemHashMap.put(goodsItem.itemEntity.getId(), getItemById(goodsItem.itemEntity.getId()));
        }
        cartView.setQuantityText(totalCount);
        cartListAdapter.notifyDataSetChanged();
        if (isNotifyData)
            notifyData();
        observable.notifyObservers(cartBean);
    }

    @Override
    public void minusSubItem(SubCartBean subCartBean, PinedSectionAdapter.GoodsItem goodsItem) {
        minusSubItem(subCartBean,goodsItem,false);
    }

    public void minusSubItem(SubCartBean subCartBean, PinedSectionAdapter.GoodsItem goodsItem, boolean isNotifyData) {
        goodsItems.get(goodsItem.listPosition).count -= subCartBean.getCount();
        categoryList.get(goodsItem.sectionPosition).sectionContainCount -= subCartBean.getCount();
        summery -= (Integer.parseInt(goodsItem.itemEntity.getPrice()) * subCartBean.getCount());
        totalCount -= subCartBean.getCount();
        double result = Double.parseDouble(String.valueOf(summery));
        cartView.setSummery(String.format("%.2f", result / 100));
        cartView.setQuantityText(totalCount);


        CartBean cartBean = getCartBeanPosition(goodsItem.itemEntity.getId());
        if (cartBean != null) {
            if (cartBean.item_nums.equals("1")) {
                cartList.remove(cartBean);
                cartBean.item_nums = "0";
            } else {
                cartBean.item_nums = String.valueOf(Integer.parseInt(cartBean.item_nums) - subCartBean.getCount());
            }
            int currentSubPosition = -1;
            for (int i = 0; i < cartBean.goodsInfo.subList.size(); i++) {
                if (cartBean.goodsInfo.subList.get(i).getPropertyMap().values().containsAll(subCartBean.getPropertyMap().values())) {
                    currentSubPosition = i;
                }
            }
            if (currentSubPosition != -1) {
                int newCount = cartBean.goodsInfo.subList.get(currentSubPosition).getCount() - subCartBean.getCount();
                if (newCount < 1) {
                    cartBean.goodsInfo.subList.remove(currentSubPosition);
                } else {
                    cartBean.goodsInfo.subList.get(currentSubPosition).setCount(newCount);
                }
            }
        }
        if (selectedGoodsItemHashMap.containsKey(goodsItem.itemEntity.getId()) && goodsItems.get(goodsItem.listPosition).count == 0) {
            selectedGoodsItemHashMap.remove(goodsItem.itemEntity.getId());
            notifyData();
        } else if (isNotifyData)
            notifyData();
        cartListAdapter.notifyDataSetChanged();
        observable.notifyObservers(cartBean);
    }
}
